package cs342.uwosh.edu.QuizApp.thread;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutionException;

import android.os.AsyncTask;

//Allows threading for any object and any object method

public class AsyncMethod<T> extends AsyncTask<Object, Object, Object> {
	private Class<T> theClass;
	private Object object;
	private String methodName;
	public AsyncMethod(Class<T> objectClass, T object, String methodName) {
		this.theClass = objectClass;
		this.object = object;
		this.methodName = methodName;
	}
	
	public void setMethod(String methodName) {
		this.methodName = methodName;
	}
	
	protected Object doInBackground(Object... args)
	{
			
		@SuppressWarnings("rawtypes")
		Class[] argClasses = new Class[args.length];
		for(int i = 0; i < args.length; i++) {
			argClasses[i] = args[i].getClass();
		}
		Method method = null;
		Method[] methods = theClass.getMethods();
		System.out.println(methods);
		try {
			method = theClass.getMethod(methodName, argClasses);
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		}
		
		Object obj = null;
		try {
			obj = method.invoke(object, args);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return obj;
	}
	public Object getResult() {
		Object obj = null;
		
		try {
			obj = this.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		return obj;
	}
}
